package route

import (
	"fmt"
	"alisms/model"

	"github.com/kataras/iris"
	"github.com/kataras/iris/context"
	"github.com/go-xorm/xorm"
   _ "github.com/mattn/go-sqlite3"
)

type templ struct {
}
func (m templ) Getall(ctx context.Context) {
	orm, err := xorm.NewEngine("sqlite3", "./data/test.db")
    if err != nil {
        fmt.Println(err)
    }
    iris.RegisterOnInterrupt(func() {
        orm.Close()
    })
	  templ := []model.Templ{}
	  orm.Sql("select * from Templ").Find(&templ)
	  fmt.Println(templ)
      //ctx.Writef("user: %#v", user)
      ctx.JSON(map[string]interface{}{"success": "success","templ":templ})
}
func (m templ) Save(ctx context.Context) {
	var op model.Templ
	ctx.ReadJSON(&op)
	//
	orm, err := xorm.NewEngine("sqlite3", "./data/test.db")
    if err != nil {
        fmt.Println(err)
    }
    iris.RegisterOnInterrupt(func() {
        orm.Close()
	})
	err = orm.Sync2(new(model.Templ))
    if err != nil {
        fmt.Println(err)
	}
	//
	//var errmsg string
	fmt.Println(op.Id)
	if op.Id == 0{
		templ := model.Templ{Name: op.Name ,Code: op.Code ,Cont: op.Cont}
		_ ,err:= orm.Insert(templ)
		ctx.JSON(map[string]interface{}{"errmsg":err})
	}else{
		// templ := model.Templ{Id: op.Id}
		// fmt.Println(templ)
		
		// templ.Name=op.Name
		sql:="update Templ set name=?,Code=?,Cont=? where Id=?"
		num ,err:= orm.Exec(sql,op.Name, op.Code, op.Cont, op.Id)
		fmt.Println(num)
		ctx.JSON(map[string]interface{}{"errmsg":err})
	}
   // ctx.JSON(map[string]interface{}{"errmsg":err})
        //ctx.Writef("user inserted: %#v", user)
      
}
func (m templ) Del(ctx context.Context) {
	var op model.Ids
	ctx.ReadJSON(&op)
	
	orm, err := xorm.NewEngine("sqlite3", "./data/test.db")
    if err != nil {
        fmt.Println(err)
    }
    iris.RegisterOnInterrupt(func() {
        orm.Close()
	})
	for _, id := range op.Ids {
		templ := model.Templ{Id:id}
		orm.Delete(templ)
	}

      ctx.JSON(map[string]interface{}{"success": "success"})
}

